package com.agy.filemanager.controller;

import com.agy.filemanager.common.TreeUtil;
import com.agy.filemanager.entity.DcBaseUserRole;
import com.agy.filemanager.entity.TreeModel;
import com.agy.filemanager.service.DcSystemBaseUserRoleService;
import com.agy.filemanager.toolClass.Result;
import com.agy.filemanager.toolClass.ResultUtil;
import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.UUID;


/**
 * 系统设置-人员角色维护
 */
@Controller
@RequestMapping("/systembaseuserrole")
public class SystemBaseUserRoleController {

    @Autowired
    private DcSystemBaseUserRoleService dcBaseUserRoleService;

    /**
     * 获取安工院人员组织机构树
     * @return
     */
    @PostMapping("/agyusertree")
    @ResponseBody
    public Result getAgyuserTree(){
        List<TreeModel> list = TreeUtil.getTree(dcBaseUserRoleService.getAgyuserTree());
        return ResultUtil.success(list, "成功");
    }

    /**
     * 保存人员角色关系
     * @return
     */
    @PostMapping(value = "/saveuserrole",produces = "application/json;charset=UTF-8")
    @ResponseBody
    public Result saveUserRole(HttpServletRequest request){
        List<DcBaseUserRole> userRoleList = null;
        try {
            JSONObject jsonObject = new JSONObject(request.getParameter("userRoleJSON"));//获取json对象
            String userId = jsonObject.getString("userId");//通过键值名获取字符串
            JSONArray roleId_jsonArray = jsonObject.getJSONArray("roleId");//通过键值名获取数组格式的json对象
            DcBaseUserRole dcBaseUserRole = new DcBaseUserRole();
            dcBaseUserRoleService.deleteByUserId(userId);
            dcBaseUserRole.setUserId(userId);
            for (int i = 0; i < roleId_jsonArray.length(); i++) {
                String roleId = roleId_jsonArray.getString(i);
                dcBaseUserRole.setRoleId(roleId);
                String id = UUID.randomUUID().toString().replaceAll("-", "");
                dcBaseUserRole.setId(id);
                dcBaseUserRoleService.saveUserRole(dcBaseUserRole);
            }
            userRoleList = dcBaseUserRoleService.getUserRole(userId);
        }catch (Exception e){
            e.printStackTrace();
        }
        return ResultUtil.success(userRoleList, "成功");
    }

    @PostMapping("/getuserrole")
    @ResponseBody
    public Result getUserRole(String userId){
        List<DcBaseUserRole> userRole = null;
        try{
            userRole = dcBaseUserRoleService.getUserRole(userId);
        } catch ( Exception ex){
            ex.printStackTrace();
        }
        return ResultUtil.success(userRole,"请求成功");
    }





}
